package com.sky.service.impl;

import com.sky.dto.DataReportDTO;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public Result<TurnoverReportVO> turnoverStatistics(DataReportDTO dataReportDTO) {
        //获取请求数据
        LocalDate begin = dataReportDTO.getBegin();
        LocalDate end = dataReportDTO.getEnd();

        //定义集合用于存放每日营业额数据
        List<Double> turnoverList=new ArrayList<Double>();
        //将日期集合抽取为方法直接调用
        List<LocalDate> dateList = getdataList(begin, end);
        for (LocalDate localDate : dateList) {
            //获取开始时间和结束时间的时分秒数据
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //统计每日营业额数据
            Double turnover=reportMapper.turnover(beginTime,endTime,Orders.COMPLETED);
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        //定义封装数据
        TurnoverReportVO turnoverReportVO =TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return Result.success(turnoverReportVO);
    }

    @Override
    public Result<UserReportVO> userStatistics(DataReportDTO dataReportDTO) {
        //获取请求数据
        LocalDate begin = dataReportDTO.getBegin();
        LocalDate end = dataReportDTO.getEnd();
        //定义用户总量集合
        List<Integer> totalUserList=new ArrayList<>();
        //定义新增用户集合
        List<Integer> newUserList=new ArrayList<>();

        //将日期集合抽取为方法直接调用
        List<LocalDate> dateList=getdataList(begin, end);
        for (LocalDate localDate : dateList) {
            //获取开始时间和结束时间的时分秒数据
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //统计用户总量
            Integer totaluser=reportMapper.totaluser(endTime);
            totaluser=totaluser==null?0:totaluser;
            totalUserList.add(totaluser);
            //统计新增用户数量
            Integer newUser=reportMapper.newUser(beginTime,endTime);
            newUser=newUser==null?0:newUser;
            newUserList.add(newUser);
        }
        UserReportVO userReportVO =UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
        return Result.success(userReportVO);
    }

    @Override
    public Result<OrderReportVO> ordersStatistics(DataReportDTO dataReportDTO) {
        //获取请求数据
        LocalDate begin = dataReportDTO.getBegin();
        LocalDate end = dataReportDTO.getEnd();
        //统计整个区间范围内的订单数
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //每日订单总数
        List<Integer> totalorderCountList=new ArrayList<>();
        //每日有效订单数
        List<Integer> validOrderCountList=new ArrayList<>();
        //订单总数
        Integer totalOrderCount=reportMapper.OrderCount(beginTime,endTime,null);
        //有效订单数
        Integer validOrderCount=reportMapper.OrderCount(beginTime,endTime,Orders.COMPLETED);
        //订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        }
        //将日期集合抽取为方法直接调用
        List<LocalDate> dateList=getdataList(begin, end);
        //统计每一天的订单
        for (LocalDate localDate : dateList) {
            //获取开始时间和结束时间的时分秒数据
            LocalDateTime dailyBeginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime dailyEndTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //每日有效订单数
            Integer dailyOrderCount=reportMapper.OrderCount(dailyBeginTime,dailyEndTime,Orders.COMPLETED);
            dailyOrderCount=dailyOrderCount==null?0:dailyOrderCount;
            validOrderCountList.add(dailyOrderCount);
            //每日订单总数
            Integer dailyTotalOrderCount=reportMapper.OrderCount(dailyBeginTime,dailyEndTime,null);
            dailyTotalOrderCount=dailyTotalOrderCount==null?0:dailyTotalOrderCount;
            totalorderCountList.add(dailyTotalOrderCount);
        }
        //定义封装数据
        OrderReportVO orderReportVO = OrderReportVO.
                builder()
                .dateList(StringUtils.join(dateList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCountList(StringUtils.join(totalorderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return Result.success(orderReportVO);

    }

    @Override
    public Result<SalesTop10ReportVO> top10(DataReportDTO dataReportDTO) {
        //获取请求数据
        LocalDate begin = dataReportDTO.getBegin();
        LocalDate end = dataReportDTO.getEnd();

        //定义商品名称列表
        List<String> nameList=new ArrayList<>();
        //定义销量列表
        List<Integer> numberList=new ArrayList<>();

        //统计整个区间范围内的最大时间和最小时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //获取这个范围内所有的订单id
        List<Long> orderIds=reportMapper.getOrder(beginTime,endTime,Orders.COMPLETED);
        //根据订单id,查询订单详情表，判断这个时间段内什么菜品销量最高，取前10
        List<GoodsSalesDTO> goodsSalesDTOList=reportMapper.salesTop10(orderIds);
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
        //定义封装对象
        SalesTop10ReportVO salesTop10ReportVO=SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
        return Result.success(salesTop10ReportVO);
    }

    @Override
    public void export(HttpServletResponse response)  {
        try {
            //查询数据库获取营业数据
            LocalDate dataBegin = LocalDate.now().minusDays(30);
            LocalDate dataEnd = LocalDate.now().plusDays(1);
            LocalDateTime beginDateTime = LocalDateTime.of(dataBegin, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(dataEnd, LocalTime.MAX);
            BusinessDataVO businessData = workspaceService.getBusinessData(beginDateTime, endDateTime);

            //通过POI将数据写入到Excel文件中
            FileInputStream fileInputStream = new FileInputStream(new File("D:\\workspace\\Pro2_sky\\sky-take-out\\运营数据报表模板.xlsx"));
            //基于模板那文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);

            //填充数据--时间
            XSSFSheet sheet = excel.getSheetAt(0);
            //第二行插入时间范围区间
            sheet.getRow(1).getCell(1).setCellValue("时间:" + dataBegin + "至" + dataEnd);

            //填充概览数据
            //获得第四行
            XSSFRow row = sheet.getRow(3);
            //向第四行第3、5、7个单元格依次插入营业额、订单完成率、新增客户数
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获得第五行
            row = sheet.getRow(4);
            //向第五行第3、5个单元格依次插入有效订单、平均客单价
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明显数据(一个月每一天的营业额、有效订单、订单完成率、平均客单价、新增用户数)
            LocalDate Date=dataBegin.plusDays(1);
            for (int i = 0; i < 30; i++) {
                Date = Date.plusDays(1);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(Date, LocalTime.MIN), LocalDateTime.of(Date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(Date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //通过输出流将文件从浏览器导出
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private List<LocalDate> getdataList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<LocalDate>();
        dateList.add(begin);
        while(!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
